user 在使用時發現目前做出來的網格只有觀看的作用只能當作參考,draggable button 的按鈕沒有辦法對齊到線上,應使用者的要求我們今天就要為網格加入實際的功能讓按鈕可以對齊它,讓按扭有自動吸附到線上的功能。
按鈕對齊網格方法
//Frame.dart
Rect againstPosition(DraggableInfo info, Rect mRect) {
//半格
double size = spacePainter.gridSize / 2;
double left, top, right, bottom;
//位移 = (按鈕左邊位置 - 網格開始位置)%半格寬度
//取餘數後得到的值就是等等要為位移的大小
double offsetX = (mRect.left - spacePainter.startX) % size;
if (offsetX < size / 2) {
left = mRect.left - offsetX;
} else {
left = mRect.left - offsetX + size ;
}
//同橫向移動
double offsetY = (mRect.top- spacePainter.startY) % size;
if (offsetY < size / 2) {
top = mRect.top - offsetY;
} else {
top = mRect.top - offsetY+size;
}
right = left + mRect.width;
bottom = top + mRect.height;
if (top < spacePainter.startY) {
top = spacePainter.startY;
bottom = top + mRect.height;
}
if (left < spacePainter.startX) {
left = spacePainter.startX;
right = left + mRect.width;
}
if (bottom > spacePainter.endY) {
bottom = spacePainter.endY;
}
if (right > spacePainter.endX) {
right = spacePainter.endX;
}
return Rect.fromLTRB(left, top, right, bottom);
}
將 againstPosition 加入到 children 生成中,去改變按鈕的位置
//Frame.dart
@override
Widget build(BuildContext context) {
final spacePaint = CustomPaint(painter: spacePainter) ;
List<Widget> children = List.generate(data.length, (index) {
var draggableBtn = RaisedButton(child: Text(data[index].text) ,onPressed: (){},);
Rect rect = fixRect(context, data[index]) ;
+ rect = againstPosition(data[index], rect) ;
return Positioned.fromRect(
rect: rect ,
child: draggableBtn
);
});
children.insert(0, spacePaint) ;
children.insert(0,Positioned.fill(child: Container(color: Colors.grey,)));
return Stack(
fit: StackFit.expand,
children:children,
) ;
}
範例圖示